//
//  DDWoRootVC.m
//  dingdang
//
//  Created by 阮 沧晖 on 15/6/28.
//  Copyright (c) 2015年 阮 沧晖. All rights reserved.
//

#import "DDWoRootVC.h"
#import "GlobalDefine.h"
#import "UIImageView+WebCache.h"
#import "DDLoginRootVC.h"
#import "DDNetWorkAPIClient.h"
#import "DDWoIntegralVC.h"
#import "DDExchangeVC.h"
#import "DDCollectionVC.h"
#import "DDMessageRootVC.h"
#import "DDMyAnswerVC.h"
#import "DDSign.h"
#import "DDMyQuestionViewController.h"
#import "DDWoInfoVC.h"
#import "DDSetting.h"
#import "DDFeekBack.h"
#import "DDIntegralExchange.h"

@interface DDWoRootVC ()<UIGestureRecognizerDelegate>

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic,strong) NSMutableArray *datas;
@property (nonatomic,strong) NSMutableArray *imageDatas;
@property (weak, nonatomic) IBOutlet UIImageView *headerImageView;
@property (weak, nonatomic) IBOutlet UIButton *cd_btn;
@property (weak, nonatomic) IBOutlet UILabel *headerName;
@property (weak, nonatomic) IBOutlet UILabel *rankLabel;
@property (weak, nonatomic) IBOutlet UILabel *dingdangID;

@property (nonatomic,strong)DDNetWorkAPIClient *network ;
@property (nonatomic,strong)NSString * intgeral;
@end

@implementation DDWoRootVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    [self createData];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (void)viewWillAppear:(BOOL)animated
{
    [self createUI];
    
    self.navigationController.navigationBar.hidden = YES;
    [super viewWillAppear:animated];
    
  
        [_network queryIntegral:^(BOOL isSuccess, NSDictionary *dict, NSString *message, NSString *status) {
            NSLog(@"%@",dict);
            if (isSuccess) {
                _intgeral = [[dict objectForKey:@"integral"]stringValue];
                [self.tableView reloadData];
            }
        }];
}

- (void)createUI
{
    self.tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 0.01)];

    self.navigationController.navigationBar.hidden = YES;
    DDSharedUser *user = [DDSharedUser shared];
    NSString * url = user.userInfo.avatarUrl==nil?@"":user.userInfo.avatarUrl;
    [_headerImageView sd_setImageWithURL:[NSURL URLWithString:url] placeholderImage:[UIImage imageNamed:@"首页列表头像-通用"]options:SDWebImageRefreshCached];
    _headerImageView.layer.cornerRadius = 40.0;
    _headerImageView.layer.masksToBounds = YES;
    _headerName.text = user.userInfo.nickName;
    
 
    
    _cd_btn.layer.cornerRadius = 10;
    _cd_btn.layer.masksToBounds = YES;
    _cd_btn.layer.borderWidth = 1.0;
    _cd_btn.layer.borderColor = [UIColor whiteColor].CGColor;
}
- (IBAction)userinfoAction:(id)sender {
    NSLog(@"3333");
    DDWoInfoVC *woinfo = [[DDWoInfoVC alloc]initWithNibName:@"DDWoInfoVC" bundle:nil];
    woinfo.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:woinfo animated:YES];
    
    //[[NSNotificationCenter defaultCenter] postNotificationName:@"ToDetailPage" object:woinfo];
}

- (void)createData
{
 
    NSArray * firstGroup = @[@"我的积分",@"积分兑换"];
    NSArray * secondGroup = @[@"我的发问",@"我的回答",@"我的收藏",@"我的消息"];
    
    _datas =  [NSMutableArray array];
    [_datas addObject:firstGroup];
    [_datas addObject:secondGroup];
    
    NSArray * imageFristGroup = @[@"我的积分图标",@"积分兑换图标"];
    NSArray * imageSecondGroup = @[@"我的发问图标",@"我的答疑图标",@"我的收藏图标",@"我的答疑图标"];
    _imageDatas = [NSMutableArray array];
    [_imageDatas addObject:imageFristGroup];
    [_imageDatas addObject:imageSecondGroup];
    
    DDSharedUser *user = [DDSharedUser shared];

    self.rankLabel.text = user.userInfo.rank;
    self.dingdangID.text = [NSString stringWithFormat:@"丁当号:%@", user.userInfo.no];
    
    _network = [[DDNetWorkAPIClient alloc]init];
    
    
}


#pragma mark -UITableDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [_datas[section] count];
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return _datas.count;
}
- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 44;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section

{
    if (section == 1) {
         return 74;
    }
   
    return 0;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{

    if (section == 1) {
        UIView * footView =[[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, tableView.frame.size.width, 74)];
        //[footView setBackgroundColor:[UIColor whiteColor]];
        
        UIButton *logoutButton = [UIButton buttonWithType:UIButtonTypeCustom];
        logoutButton.frame = CGRectMake( 10, 15, tableView.frame.size.width - 20, 54);
        logoutButton.layer.cornerRadius = 5.0;
        [logoutButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [logoutButton setTitle:@"退出登录" forState:UIControlStateNormal];
        [logoutButton setBackgroundColor:RGB(46,187,232)];
        [logoutButton addTarget:self action:@selector(logOutAction:) forControlEvents:UIControlEventTouchUpInside];
        logoutButton.titleLabel.font = [UIFont fontWithName:@"Arial" size:22.0];
        [logoutButton setTitleEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 0)];
        [logoutButton setImageEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 0)];
        [footView addSubview:logoutButton];
        return footView;
    }
    return nil;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"UITableViewCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        cell.accessoryType=UITableViewCellAccessoryDisclosureIndicator;
    }
    for (UIView *view in cell.contentView.subviews) {
        [view removeFromSuperview];
    }
    if (indexPath.section == 0 && indexPath.row == 0) {
       
        if (_intgeral) {
            UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(self.tableView.frame.size.width-150, 7, 120, 30)];
            label.text =_intgeral;
            label.textColor = [UIColor lightGrayColor];
            label.textAlignment = NSTextAlignmentRight;
            label.font = [UIFont fontWithName:@"Arial" size:18.0];
            [cell.contentView addSubview:label];
        }
    }

    UIImageView *iconImageView = [[UIImageView alloc] initWithFrame:CGRectMake(10, 6, 32, 32)];
    iconImageView.image = [UIImage imageNamed:_imageDatas[indexPath.section][indexPath.row]];
    [cell.contentView addSubview:iconImageView];
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake([self xPostiong:iconImageView sp:20], 10, cell.frame.size.width, 24)];
    label.text = _datas[indexPath.section][indexPath.row];
    label.font = [UIFont fontWithName:@"Arial" size:20.0];
    [cell.contentView addSubview:label];

    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    self.navigationController.navigationBarHidden = NO;
    if (indexPath.row == 0 && indexPath.section == 0) {
        DDWoIntegralVC *woIntegralVC = [[DDWoIntegralVC alloc]initWithNibName:@"DDWoIntegralVC" bundle:nil];
        woIntegralVC.intgeral = _intgeral;
        woIntegralVC.hidesBottomBarWhenPushed = YES;
        //[[NSNotificationCenter defaultCenter] postNotificationName:@"ToDetailPage" object:woIntegralVC];
        [self.navigationController pushViewController:woIntegralVC animated:YES];
    }
    if (indexPath.row == 1 && indexPath.section == 0) {
        //DDExchangeVC *exchangeVC = [[DDExchangeVC alloc]initWithNibName:@"DDExchangeVC" bundle:nil];
        DDIntegralExchange *gift = [[DDIntegralExchange alloc]initWithNibName:@"DDIntegralExchange" bundle:nil];
        gift.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:gift animated:YES];
        //[[NSNotificationCenter defaultCenter] postNotificationName:@"ToDetailPage" object:gift];
        
        
        //[self.navigationController pushViewController:woIntegralVC animated:YES];
    }
    if (indexPath.row == 0 && indexPath.section == 1) {
        DDMyQuestionViewController * myQuestionVc= [[DDMyQuestionViewController alloc]init];
        myQuestionVc.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:myQuestionVc animated:YES];
    }
    if (indexPath.row == 1 && indexPath.section == 1) {
        DDMyAnswerVC *answerVC = [[DDMyAnswerVC alloc]initWithNibName:@"DDMyAnswerVC" bundle:nil];
        //answerVC.navigationController.navigationBarHidden = NO;
        // [[NSNotificationCenter defaultCenter] postNotificationName:@"ToDetailPage" object:answerVC];
        answerVC.hidesBottomBarWhenPushed = YES;
       [self.navigationController pushViewController:answerVC animated:YES];
    }
    
    if (indexPath.row == 2 && indexPath.section == 1) {
        DDCollectionVC *collectionVC = [[DDCollectionVC alloc]initWithNibName:@"DDCollectionVC" bundle:nil];
        
        //[self.navigationController pushViewController:collectionVC animated:YES];
         collectionVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:collectionVC animated:YES];
        //[[NSNotificationCenter defaultCenter] postNotificationName:@"ToDetailPage" object:collectionVC];
    }
    
    if (indexPath.row == 3 && indexPath.section == 1) {
        DDMessageRootVC *messageRootVC = [[DDMessageRootVC alloc]initWithNibName:@"DDMessageRootVC" bundle:nil];
        
        //[self.navigationController pushViewController:collectionVC animated:YES];
        messageRootVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:messageRootVC animated:YES];
        //[[NSNotificationCenter defaultCenter] postNotificationName:@"ToDetailPage" object:collectionVC];
    }
    
}


-(float) xPostiong:(UIView *)view sp:(float)sp
{
    return view.frame.size.width+view.frame.origin.x + sp;
}

-(float) yPostiong:(UIView *)view sp:(float)sp
{
    return view.frame.size.height+view.frame.origin.y + sp;
}


- (void)logOutAction:(UIButton *)sender
{
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"你确定退出登录" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    [alertView show];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1) {
        DDSharedUser *user = [DDSharedUser shared];
        [user updateUserDefaults:@"" forKey:kPassword];
        
        DDLoginRootVC *loginVC = [[DDLoginRootVC alloc]initWithNibName:@"DDLoginRootVC" bundle:nil];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"ToDetailPage" object:loginVC];
        //[self.navigationController pushViewController:loginVC animated:YES];
    }
}
- (IBAction)sign:(id)sender {
   [_network dailySign:^(BOOL isSuccess, NSDictionary *dict, NSString *message, NSString *status) {
        NSLog(@"%@",dict);
        if (isSuccess) {
            DDSharedUser *user = [DDSharedUser shared];
            DDUser *userinfo = user.userInfo;
            DDSign *sign = [DDSign searchSingleWithWhere:[NSString stringWithFormat:@"time='%@' AND userid='%@'",[self getCurrentDate],userinfo.no] orderBy:nil];
            if (!sign) {
                sign = [[DDSign alloc] init];
                sign.time = [self getCurrentDate];
                
                sign.userid = userinfo.no;
                sign.point = @"10";
                [sign saveToDB];
                [_network queryIntegral:^(BOOL isSuccess, NSDictionary *dict, NSString *message, NSString *status) {
                    NSLog(@"%@",dict);
                    if (isSuccess) {
                        _intgeral = [[dict objectForKey:@"integral"]stringValue];
                        [self.tableView reloadData];
                    }
                }];
                [self delayHUD:message];
                
            }else{
                [self delayHUD:@"您今天已经签到了"];
            }
           
        }else{
            [self delayHUD:@"已签到过了"];
        }
    }];
}

- (IBAction)setting:(id)sender{
    DDSetting *vc = [[DDSetting alloc]initWithNibName:@"DDSetting" bundle:nil];
//    DDFeekBack *vc = [[DDFeekBack alloc]initWithNibName:@"DDFeekBack" bundle:nil];
    vc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc animated:YES];
}

-(NSString *)getCurrentDate
{
    NSDate *  senddate=[NSDate date];
    
    NSDateFormatter  *dateformatter=[[NSDateFormatter alloc] init];
    
    [dateformatter setDateFormat:@"YYYYMMdd"];
    
    NSString *  locationString=[dateformatter stringFromDate:senddate];
    
    NSLog(@"locationString:%@",locationString);
    return locationString;
}
@end
